<?php
/**
 * 地区管理
 * 
 * @author Ansion <1572309495@qq.com>
 * @since  2015-7-1
 */
/**
 * 地区管理
 * 
 * @author Ansion <1572309495@qq.com>
 */
 
namespace Admin\Controller;

use System\Controller;
use \Org\Com\Tool;

//引用无限分级类
use Think\Tree;

class AreaController extends CommonController{
	public $curl = null;
	/**
    *构造函数
    *
    * @return  #     
    */
    public function _initialize()
    {
        parent::_initialize();
        $this->db = D("Area");
        //手动设置记录每页最大显示数为所有
        $_REQUEST ['listRows'] = 30;
    }
	
	/**
     * 主页
     * @return string     
    */
    public function index(){
        //列表过滤器，生成查询Map对象
        $map = $this->_search ("Area");

        //获取列表
        $list = $this->_list ( $this->db, $map, "id", true);
        $this->assign('list', $list);

        $this->display();
    }
	/**
	 *
     * 添加地区
	 *
     * @return string    
	 *
    */
    public function add()
	{
		//地区级联列表
		$data = $this->db->where("area is null")->select();
		if ($data){
			$this->assign('data', $data);
		}
		
		$this->display();
	}
	/**
	 *
     * 编辑地区
	 *
     * @return string    
	 *
    */
    public function edit()
    {
        $id = Tool::request('id', 'int');
        $vo = $this->db->find($id);

        if (!empty($vo['country'])){
                $vo['name']	=	$vo['country'];
                $code = substr($id, 0, 4);
                //区县列表
                $countryData = $this->db->where("id like '{$code}__' and state='{$vo[state]}' and id<>'{$code}00'")->order("id asc")->select();
                //城市列表
                $code = substr($id, 0, 2);
                $cityData = $this->db->where("id like '{$code}__00' and state='{$vo[state]}' and id<>'{$code}0000'")->order("id asc")->select();
                //省列表
                $provinceData = $this->db->where("id like '__0000' and state='{$vo[state]}' and id<>$id")->order("id asc")->select();
                //区块列表
                $areaData = $this->db->where("state='{$vo[state]}' and province is null and area is not null and id<>$id")->order("id asc")->select();
                //国家列表
                $stateData = $this->db->where("area is null and id<>$id")->select();

        } elseif (!empty($vo['city'])){
                $vo['name']	=	$vo['city'];
                //城市列表
                $code = substr($id, 0, 2);
                $cityData = $this->db->where("id like '{$code}__00' and state='{$vo[state]}' and id<>'{$code}0000'")->order("id asc")->select();
                //省列表
                $provinceData = $this->db->where("id like '__0000' and state='{$vo[state]}' and id<>$id")->order("id asc")->select();
                //区块列表
                $areaData = $this->db->where("state='{$vo[state]}' and province is null and area is not null and id<>$id")->order("id asc")->select();
                //国家列表
                $stateData = $this->db->where("area is null")->select();
        } elseif (!empty($vo['province'])){
                $vo['name']	=	$vo['province'];
                //省列表
                $provinceData = $this->db->where("id like '__0000' and state='{$vo[state]}' and id<>$id")->order("id asc")->select();
                //区块列表
                $areaData = $this->db->where("state='{$vo[state]}' and province is null and area is not null and id<>$id")->order("id asc")->select();
                //国家列表
                $stateData = $this->db->where("area is null")->select();
        } elseif (!empty($vo['area'])){
                $vo['name']	=	$vo['area'];
                //区块列表
                $areaData = $this->db->where("state='{$vo[state]}' and province is null and area is not null and id<>$id")->order("id asc")->select();
                //国家列表
                $stateData = $this->db->where("area is null and id<>$id")->select();
        } else {
                $vo['name']	=	$vo['state'];
                //国家列表
                $stateData = $this->db->where("area is null and id<>$id")->select();
        }

        $this->assign('countryData', $countryData);
        $this->assign('cityData', $cityData);
        $this->assign('provinceData', $provinceData);
        $this->assign('areaData', $areaData);
        $this->assign('stateData', $stateData);
        $this->assign('vo', $vo);

        $this->display();
    }
	/**
	 *
     * 保存记录
	 *
     * @return string
	 *
    */
	function save() {
		//是否为修改标志
		$isUpdate = true;
		if (!empty($_POST['isAdd'])){
			//为新增
			$isUpdate = false;
		}
		$name = Tool::request('name', 'text');
		unset($_POST['name']);
		unset($_POST['isAdd']);
		//组装数据
		if (empty($_POST['state'])){
			//操作对象为-国家
			$_POST['state'] 	= $name;
			unset($_POST['area']);
			unset($_POST['province']);
			unset($_POST['city']);
			unset($_POST['country']);
		} elseif (empty($_POST['area'])){
			//操作对象为-区块
			$_POST['area'] 	= $name;
			unset($_POST['province']);
			unset($_POST['city']);
			unset($_POST['country']);
		} elseif (empty($_POST['province'])){
			//操作对象为-省
			$tempInfo= $this->db->where("id={$_POST['area']}")->find();
			$_POST['area'] 		= $tempInfo['area'];
			$_POST['state'] 	= $tempInfo['state'];
			$_POST['province']	= $name;
		} elseif (empty($_POST['city'])){
			//操作对象为-城市
			$tempInfo= $this->db->where("id={$_POST['province']}")->find();
			$_POST['state'] 	= $tempInfo['state'];
			$_POST['area'] 		= $tempInfo['area'];
			$_POST['province'] 	= $tempInfo['province'];
			$_POST['city'] 		= $name;
		} elseif (empty($_POST['country'])){
			//操作对象为-区/县
			$tempInfo= $this->db->where("id={$_POST['city']}")->find();
			$_POST['state'] 	= $tempInfo['state'];
			$_POST['area'] 		= $tempInfo['area'];
			$_POST['province'] 	= $tempInfo['province'];
			$_POST['city'] 		= $tempInfo['city'];
			$_POST['country'] 	= $name;
		}

		if (false === $this->db->create ()) {
			$this->error($this->db->getError());
		}
		
		if ($isUpdate){
			// 更新数据
			$rs=$this->db->save ();
			if($rs){
				//添加系统日志
				$data['tableName'] 	= "area";
				$data['tableKeyId'] = $_POST['id'];
				$data['remark'] 	= "更新了名为【{$_POST['area']}-{$_POST['province']}-{$_POST['city']}-{$_POST['country']}】的地区";
				$this->addLog($data);
			}
		} else {
			//插入数据
			$rs=$this->db->add ();
			if($rs){
				//添加系统日志
				$data['tableName'] 	= "area";
				$data['tableKeyId'] = $rs;
				$data['remark'] 	= "添加了名为【{$_POST['area']}-{$_POST['province']}-{$_POST['city']}-{$_POST['country']}】的地区";
				$this->addLog($data);
			}
		}
		//echo $this->db->getlastsql();
		
		if ($rs) {
			$this->dwzSuccess('保存成功!');
		} else {
			//错误提示
			$this->error('保存失败!');
		}
	}
	/**
	 *
     * 删除指定记录
	 *
     * @return string
	 *
    */
	public function del() {
		$id = Tool::request("id", 'int');
		//首先判断是否存在下级
		$tempData = $this->db->find($id);
		if (!$tempData){
			$this->error ( '参数错误' );
		}
		if (empty($tempData['area'])){
			//删除国家
			$rs = $this->db->where("state='{$tempData[state]}' and id<>$id")->find();
			if ($rs){
				$this->error ( '存在下级，请先删除' );
			}
		} elseif (empty($tempData['province'])){
			//删除区块
			$rs = $this->db->where("area='{$tempData[area]}' and id<>$id")->find();
			if ($rs){
				$this->error ( '存在下级，请先删除' );
			}
		} elseif (empty($tempData['city'])){
			//删除省
			$rs = $this->db->where("province='{$tempData[province]}' and id<>$id")->find();
			if ($rs){
				$this->error ( '存在下级，请先删除' );
			}
		} elseif (empty($tempData['country'])){
			//删除城市
			$rs = $this->db->where("city='{$tempData[city]}' and id<>$id")->find();
			if ($rs){
				$this->error ( '存在下级，请先删除' );
			}
		}
		
		if (isset ( $id )) {
			$rs = $this->db->where("id=$id")->find();
			$condition = array ("id" => array ('in', explode ( ',', $id ) ) );
			if (false !== $this->db->where ( $condition )->delete ()) {
				//添加系统日志
				$data['tableName'] 	= "area";
				$data['tableKeyId'] = $id;
				$data['remark'] 	= "删除了地区（ID：{$id}，区块：$rs[area]，省：$rs[province]，市：$rs[city]，县：$rs[country]）";
				$this->addLog($data);
				$this->success ( '删除成功' );
			} else {
				$this->error ( '删除失败' );
			}	
		} else {
			$this->error ( '非法操作' );
		}
	}
	/**
	 *
     * ajax显示所在区块
	 *
     * @return json
	 *
    */
	public function ajaxShowQukuai() {
		$state = Tool::request('id', 'trim');
		if (empty($state)){
			$data = array(
				array('', '区块'),
			);
			echo json_encode($data);
			exit;
		}
		//获取区块
		$areaData = $this->db->where("state='{$state}' and province is null and area is not null")->order("id asc")->select();
		if ($areaData){
			$data = array();
			$data[0] = array('', '区块');
			foreach($areaData as $k => $v){
				$data[$k+1] = array($v['id'], $v['area']);
			}
			echo json_encode($data);
			exit;
		} else {
			$data = array(
				array('', '区块'),
			);
			echo json_encode($data);
			exit;
		}
	}
	/**
	 *
     * ajax显示省列表
	 *
     * @return json
	 *
    */
	public function ajaxShowProvince() {
		$id = Tool::request('id', 'trim');
		if (empty($id)){
			$data = array(
				array('', '省级'),
			);
			echo json_encode($data);
			exit;
		}
		$area = $this->db->where("id={$id}")->getField("area");
		if (empty($area)){
			$data = array(
				array('', '省级'),
			);
			echo json_encode($data);
			exit;
		}
		//获取省
		$tempData = $this->db->where("area='{$area}' and city='' and province is not null")->order("id asc")->select();
		//dump($tempData);
		if ($tempData){
			$data = array();
			$data[0] = array('', '省级');
			foreach($tempData as $k => $v){
				$data[$k+1] = array($v['id'], $v['province']);
			}
			echo json_encode($data);
			exit;
		} else {
			$data = array(
				array('', '省级'),
			);
			echo json_encode($data);
		}
	}
	/**
	 *
     * ajax显示城市列表
	 *
     * @return json
	 *
    */
	public function ajaxShowCity() {
		$id = Tool::request('id', 'trim');
		if (empty($id)){
			$data = array(
				array('', '选择城市'),
			);
			echo json_encode($data);
			exit;
		}
		$code = substr($id, 0, 2);
		//获取城市
		$cityData = M('Area')->where("id like '{$code}__00' and state='CN' and id<>$id")->order("id asc")->select();
		if ($cityData){
			$data = array();
			$data[0] = array('', '选择城市');
			foreach($cityData as $k => $v){
				$data[$k+1] = array($v['id'], $v['city']);
			}
			echo json_encode($data);
			exit;
		} else {
			$data = array(
				array('', '没有可选城市'),
			);
			echo json_encode($data);
			exit;
		}
	}
	/**
	 *
     * ajax显示区/县列表
	 *
     * @return json
	 *
    */
	public function ajaxShowArea() {
		$id = Tool::request('id', 'trim');
		if (empty($id)){
			$data = array(
				array('', '选择区/县'),
			);
			echo json_encode($data);
			exit;
		}
		$code = substr($id, 0, 4);
		//获取地区
		$areaData = M('Area')->where("id like '{$code}__' and state='CN' and id<>$id")->order("id asc")->select();
		if ($areaData){
			$data = array();
			$data[0] = array('', '选择区/县');
			foreach($areaData as $k => $v){
				$data[$k+1] = array($v['id'], $v['country']);
			}
			echo json_encode($data);
			exit;
		} else {
			$data = array(
				array('', '没有可选区/县'),
			);
			echo json_encode($data);
		}
	}
}